<template>
  <view class="profile-page">
    <!-- 头像部分 -->
    <view class="avatar">
      <view @click="onAvatarChange" class="avatar-content">
        <!-- 在选择新头像时，先显示本地图片 -->
        <image class="image" :src="tempAvatarPath ? tempAvatarPath : (user.photo ? loadUrl + user.photo : '/static/my/avatar.jpg')" />
        <view class="edit-icon">
          <text class="icon">✏️</text>
        </view>
      </view>
    </view>

    <!-- 表单部分 -->
    <view class="form-container">
      <view class="form">
        <!-- 表单内容 -->
        <view class="form-content">
          <view class="form-item">
            <text class="label">昵称</text>
            <input class="input" type="text" placeholder="请填写昵称" v-model="user.nickname" @input="validateNickname" />
            <text v-if="nicknameError" class="error-message">{{ nicknameError }}</text>
          </view>
          <view class="form-item">
            <text class="label">电话号码</text>
            <input class="input" type="text" placeholder="请填写电话号码" v-model="user.phone" @input="validatePhone" />
            <text v-if="phoneError" class="error-message">{{ phoneError }}</text>
          </view>
          <view class="form-item">
            <text class="label">收货地址</text>
            <view class="input-wrapper">
              <input class="input" disabled="默认收货地址" type="text" placeholder="请填写收货地址" v-model="user.defaultAddress" />
              <view class="iconfont pet-dizhi" @click="navigateToAddress"></view>
            </view>
          </view>
        </view>

        <!-- 提交按钮 -->
        <button class="form-button" @click="submitForm" :disabled="!isFormValid">保存</button>
        <view v-if="showSuccessMessage" class="success-message">修改成功！</view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user: {
        photo: '',
        nickname: '',
        phone: '',
        defaultAddress: ''
      },
      nicknameError: '',
      phoneError: '',
      showSuccessMessage: false,
      loadUrl: this.$loadUrl, // 图片服务器地址
      tempAvatarPath: '' // 临时头像路径用于本地预览
    };
  },
  mounted() {
    this.getUserData();
  },
  methods: {
    async getUserData() {
      try {
        const response = await this.$service({
          url: '/users',
          method: 'GET'
        });

        if (response.code === 0) {
          this.user = response.data;
        } else {
          uni.showToast({
            icon: 'none',
            title: '获取用户信息失败'
          });
        }
      } catch (error) {
        uni.showToast({
          icon: 'none',
          title: '网络错误，请稍后重试'
        });
      }
    },

    // 头像选择与上传
    onAvatarChange() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.tempAvatarPath = res.tempFilePaths[0]; // 预览本地图片
          this.uploadAvatar(this.tempAvatarPath); // 上传图片
        },
        fail: (error) => {
          console.error('选择图片失败:', error);
        }
      });
    },

    // 上传头像到服务器
    async uploadAvatar(filePath) {
      uni.uploadFile({
        url: this.loadUrl + '/files/upload', // 替换为实际的上传 URL
        filePath: filePath,
        name: 'file',
        success: (uploadFileRes) => {
          const data = JSON.parse(uploadFileRes.data);
          if (data.code === 0) {
            this.user.photo = data.data; // 上传成功后，使用服务器返回的图片 URL
          } else {
            uni.showToast({
              icon: 'none',
              title: '头像上传失败'
            });
          }
        },
        fail: (error) => {
          console.error('上传失败:', error);
        }
      });
    },

    // 表单提交并发起 PUT 请求
    async submitForm() {
      if (this.validateNickname() && this.validatePhone()) {
        try {
          const response = await this.$service({
            url: '/users',
            method: 'PUT',
            data: this.user
          });

          if (response.code === 0) {
            uni.showToast({
              icon: 'success',
              title: '保存成功'
            });
            this.showSuccessMessage = true;
            setTimeout(() => {
              this.showSuccessMessage = false;
            }, 3000);
          } else {
            uni.showToast({
              icon: 'none',
              title: '保存失败，请重试'
            });
          }
        } catch (error) {
          uni.showToast({
            icon: 'none',
            title: '网络错误，请稍后再试'
          });
        }
      }
    },

    // 验证昵称
    validateNickname() {
      if (!this.user.nickname) {
        this.nicknameError = '昵称不能为空';
        return false;
      } else {
        this.nicknameError = '';
        return true;
      }
    },

    // 验证手机号
    validatePhone() {
      if (!this.user.phone) {
        this.phoneError = '';
        return true;
      }
      const phoneRegex = /^\d{11}$/;
      if (!phoneRegex.test(this.user.phone)) {
        this.phoneError = '请输入正确手机号';
        return false;
      } else {
        this.phoneError = '';
        return true;
      }
    },

    // 跳转到地址管理页面
    navigateToAddress() {
      const url = '/pagesMember/addressShow/addressShow';
      uni.navigateTo({
        url: url,
        success() {
          console.log("跳转成功");
        },
        fail(error) {
          console.error("跳转失败:", error);
        }
      });
    }
  },

  computed: {
    isFormValid() {
      return this.user.nickname && !this.phoneError;
    }
  }
};
</script>

<style lang="scss">
@import '../styles.scss';

.error-message {
  color: red;
  font-size: 12px;
}
</style>
